package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.AnnualInform;
import com.cfets.annualAssessment.entity.Honor;
import com.cfets.annualAssessment.entity.Monitor;
import com.cfets.annualAssessment.entity.TableContainer;
import com.cfets.annualAssessment.service.AnnualInformService;
import com.cfets.annualAssessment.service.MonitorService;
import com.cfets.annualAssessment.util.ExcelUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * Created by ShenYiChou on 2017/1/17.
 */
@Controller
@RequestMapping("/admin/monitor")
public class MonitorController {
    @Autowired
    private MonitorService monitorService;

    @Autowired
    private AnnualInformService annualInformService;

    @RequestMapping("/index")
    public String index(Model model){
        return "monitor";
    }

    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> getMonitorList(Monitor monitor){
        List<Monitor> monitorList = monitorService.getMonitorPage(monitor);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(monitorList);
        tableContainer.setiTotalDisplayRecords(monitor.getTotalCount());
        tableContainer.setiTotalRecords(monitor.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<?> createOrUpdateMonitor(@Valid Monitor monitor, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        boolean flag = false;
        if(monitor.getId()!=null && monitor.getId()!=0){
            flag = this.monitorService.updateMonitor(monitor);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteMonitor(@PathVariable("id") int id){
        boolean flag = this.monitorService.deleteMonitorById(id);
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @RequestMapping(value = "/import",method = RequestMethod.POST)
    public ResponseEntity<?> importExcel(MultipartFile monitorFile) {
        try {
            Workbook xwb = WorkbookFactory.create(monitorFile.getInputStream());
            Sheet sheet = xwb.getSheetAt(0);
            Row row;
            for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
                if (i == 0) {
                    continue;
                }
                row = sheet.getRow(i);
                Monitor monitor = new Monitor();
                if(Objects.equals(row.getCell(1).toString(), "")){
                    return new ResponseEntity<>(-1, HttpStatus.OK);//新增失败为空 -1
                }
                AnnualInform annualInform = new AnnualInform();
                annualInform.setId_num(row.getCell(1).toString());
                if(this.annualInformService.getAnnualInform(annualInform).isEmpty()){
                    return new ResponseEntity<>(-2, HttpStatus.OK);//证件不存在 -2
                }
                monitor.setId_num(row.getCell(1).toString());

                if(Objects.equals(row.getCell(6).toString(), "")){
                    return new ResponseEntity<>(-1, HttpStatus.OK);//新增失败为空 -1
                }
                monitor.setMonitor(row.getCell(6).toString());
                monitor.setName(row.getCell(2).toString());
                monitor.setCa_num(row.getCell(3).toString());
                monitor.setOrg_name(row.getCell(4).toString());
                monitor.setDate(row.getCell(5).toString());
                if(this.monitorService.getMonitors(monitor).isEmpty()) {
                    boolean flag = this.monitorService.newMonitor(monitor);
                    if (!flag) {
                        return new ResponseEntity<>(false, HttpStatus.OK);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }
    @RequestMapping("/exportEmail")
    public String exportEmail(HttpServletResponse response){
        List<Monitor> monitorList = this.monitorService.AllMonitor();
        ExcelUtil.exportExcel("监测信息", new String[]{"NO.","姓名","证件号码","资格证书号码","机构名称","时间","监测名称"},
                new String[]{"","name","id_num","ca_num","org_name","date","monitor"}, monitorList, response );
        return null;
    }

}
